from django.core.paginator import Paginator
from rest_framework.views import APIView
from rest_framework.response import Response
from .sers import *


class IndexView(APIView):

    def get(self, request):
        # 获取分类
        queryset = Cate.objects.all()

        # ser = CateSer(queryset, many=True)
        data_list = []
        # 获取分类下的商品
        for i in queryset:
            data = {}

            data["cate"] = CateSer(i).data
            # 查找分类下的所有商品
            goods_queryset = Goods.objects.filter(cate_id=i.id)
            data["goods_list"] = GoodsSer(goods_queryset, many=True).data
            data_list.append(data)
        return Response(data_list)


class GoodsDetailView(APIView):

    def get(self, request):
        id = request.GET.get("id")

        goods = Goods.objects.filter(id=id).first()

        ser = GoodsSer(goods)

        return Response(ser.data)


class GoodsSearchView(APIView):

    def get(self, request):
        # 获取要搜索的商品名
        name = request.GET.get("name")

        # 获取页码
        num = int(request.GET.get("num", 1))

        # 根据商品名进行搜索
        queryset = Goods.objects.filter(name__contains=name)

        # 创建分页器
        paginator = Paginator(queryset, 2)

        # 根据页码获取到一页数据
        page_data = paginator.get_page(num)

        # 获取页码范围
        num_list = list(paginator.page_range)

        # 拼接数据
        data = {
            "data": GoodsListSer(page_data, many=True).data,
            "num_list": num_list
        }

        return Response(data)


class GoodsListView(APIView):

    def get(self, request):

        cid = request.GET.get("id")
        flag = request.GET.get("flag")
        print("cid", cid)
        if flag == "1":
            queryset = Goods.objects.filter(cate_id=cid)
        elif flag == "2":
            queryset = Goods.objects.filter(cate_id=cid).order_by("price")
        elif flag == "3":
            queryset = Goods.objects.filter(cate_id=cid).order_by("cat")

        ser = GoodsListSer(queryset, many=True)
        return Response(ser.data)
